package com.gin.web;

import com.gin.web.util.WebUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

/**
 * create  on 2020-03-13 11:59
 * 重新request ，把用户信息放入header里
 */
public class ApiRequestWrapper extends HttpServletRequestWrapper {

    ThreadLocal<Map<String, String>> paramLocal = new ThreadLocal<>();

    public ApiRequestWrapper(HttpServletRequest request, Map<String, String> header) {
        super(request);
        paramLocal.set(header);
    }

    @Override
    public String getHeader(String name) {
        String superData = super.getHeader(name);
        if (WebUtil.isNotBlack(superData)) {
            return superData;
        }
        Map<String, String> header = paramLocal.get();
        return header.get(name);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        Enumeration<String> superData = super.getHeaderNames();
        if (null != superData && superData.hasMoreElements()) {
            return superData;
        }
        Map<String, String> header = paramLocal.get();
        return Collections.enumeration(header.keySet());
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        Enumeration<String> superData = super.getHeaders(name);
        if (null != superData && superData.hasMoreElements()) {
            return superData;
        }
        Map<String, String> header = paramLocal.get();
        List data = Arrays.asList(header.get(name));
        return Collections.enumeration(data);
    }
}
